﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Xml;
using System.IO;
using System.Collections;

namespace Sipek
{
    class Eccp
    {

        private String response;

        private String parseError;

        private String parser;

        private int port = 20005;

        private int idRequest=0;

        private TcpClient client;

        private String cookie;

        private String agente;

        private String passwordAgente;

        private StreamWriter writer;

        private StreamReader reader;

        public void connect(String server, String usuario, String password)
        {
            try
            {
                client = new TcpClient(server, port);
                NetworkStream stream = this.client.GetStream();
                writer = new StreamWriter(stream, Encoding.UTF8);
                reader = new StreamReader(stream, Encoding.UTF8);
                loginEccp(usuario, password);
                return;
            }
            catch (Exception e)
            {
            }

        }

        private void loginEccp(String usuario,String password)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);
            XmlElement login = doc.CreateElement(string.Empty, "login", string.Empty);
            XmlElement username = doc.CreateElement(string.Empty, "username", string.Empty);
            XmlText usernameText = doc.CreateTextNode(usuario);
            XmlElement pass = doc.CreateElement(string.Empty, "password", string.Empty);
            XmlText passText = doc.CreateTextNode(MD5(password));

            username.AppendChild(usernameText);
            pass.AppendChild(passText);

            login.AppendChild(username);
            login.AppendChild(pass);
            request.AppendChild(login);
            doc.AppendChild(request);
            XmlDocument response=send_request(doc);
            this.cookie=response["response"]["login_response"]["app_cookie"].InnerText;
            return;
        }

        public XmlDocument  send_request(XmlDocument doc)
        {
            try
            {
                this.idRequest++;
                XmlElement root = doc.DocumentElement;
                root.SetAttribute("id", Convert.ToString(this.idRequest));
                String xml = root.OuterXml;
                Console.WriteLine(xml);
                writer.WriteLine(xml);
                writer.Flush();
                

                
                char[] buffer = new char[65536];
                //reader.Read(buffer, 0, buffer.Length);
                reader.ReadLine();
                response=reader.ReadLine();
                
                //stream.Close();
                //response = new String(buffer);
                XmlDocument d = new XmlDocument();
                Console.Write(response.Trim());
                d.LoadXml(response.Trim());
                return d;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return null;
            }

        }


        private  string MD5(string str)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5CryptoServiceProvider.Create();
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] stream = null;
            StringBuilder sb = new StringBuilder();
            stream = md5.ComputeHash(encoding.GetBytes(str));
            for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
            return sb.ToString();
        }

        private String agentHash()
        {

           return MD5(this.cookie + this.agente + this.passwordAgente);
        }


        public void setAgentNumber(String agente)
        {
            this.agente = agente;
        }

        public void setAgentPass(String passAgente)
        {
            this.passwordAgente = passAgente;
        }


        public String getStatusAgent()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);
            XmlElement getagentstatus = doc.CreateElement(string.Empty, "getagentstatus", string.Empty);
            XmlElement agent_number = doc.CreateElement(string.Empty, "agent_number", string.Empty);
            XmlText usernameText = doc.CreateTextNode(agente);

            doc.AppendChild(request);
            request.AppendChild(getagentstatus);
            getagentstatus.AppendChild(agent_number);
            agent_number.AppendChild(usernameText);
            XmlDocument response=send_request(doc);
            return response["response"]["getagentstatus_response"].InnerText;
        }

        public String loginAgent(String extension, String passwordExtension)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);
            XmlElement p = doc.CreateElement(string.Empty, "loginagent", string.Empty);
            XmlElement p1 = doc.CreateElement(string.Empty, "agent_number", string.Empty);
            XmlText t1 = doc.CreateTextNode(this.agente);
            p1.AppendChild(t1);
            
            XmlElement p2 = doc.CreateElement(string.Empty, "agent_hash", string.Empty);
            XmlText t2 = doc.CreateTextNode(this.agentHash());
            p2.AppendChild(t2);
            
            XmlElement p3 = doc.CreateElement(string.Empty, "extension", string.Empty);
            XmlText t3 = doc.CreateTextNode(extension);
            p3.AppendChild(t3);
            
            p.AppendChild(p1);
            p.AppendChild(p2);
            p.AppendChild(p3);
            if (passwordExtension != null)
            {
                XmlElement p4 = doc.CreateElement(string.Empty, "password", string.Empty);
                XmlText t4 = doc.CreateTextNode(passwordExtension);
                p4.AppendChild(t4);
                p.AppendChild(p4);
            }
            request.AppendChild(p);
            doc.AppendChild(request);
            XmlDocument response=send_request(doc);
            return response["response"]["loginagent_response"]["status"].InnerText;

        }

        public String logoutAgent()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);

            XmlElement p = doc.CreateElement(string.Empty, "logoutagent", string.Empty);
            XmlElement p1 = doc.CreateElement(string.Empty, "agent_number", string.Empty);
            XmlText t1 = doc.CreateTextNode(this.agente);
            p1.AppendChild(t1);
            XmlElement p2 = doc.CreateElement(string.Empty, "agent_hash", string.Empty);
            XmlText t2 = doc.CreateTextNode(this.agentHash());
            p2.AppendChild(t2);

            p.AppendChild(p1);
            p.AppendChild(p2);
            request.AppendChild(p);

            XmlDocument response=send_request(doc);
            return response["response"]["logoutagent_response"].InnerText;

        }


        public Dictionary<int,string> getPauses()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);
            XmlElement p = doc.CreateElement(string.Empty, "getpauses", string.Empty);
            request.AppendChild(p);
            doc.AppendChild(request);
            XmlDocument response = send_request(doc);
            XmlNodeList lista=response["response"]["getpauses_response"].ChildNodes;
            Dictionary<int, string> list = new Dictionary<int, string>();
            list.Add(-1, "Conectado");
            foreach (XmlNode xn in lista)
            {
                Console.WriteLine(xn.Attributes["id"].InnerText);
                
                list.Add(int.Parse(xn.Attributes["id"].InnerText),xn["name"].InnerText);
            }

                return list;
        }

        public void setPause(string pause)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);
            XmlElement p = doc.CreateElement(string.Empty, "pauseagent", string.Empty);
            XmlElement p1 = doc.CreateElement(string.Empty, "agent_number", string.Empty);
            XmlText t1 = doc.CreateTextNode(this.agente);
            p1.AppendChild(t1);
            XmlElement p2 = doc.CreateElement(string.Empty, "agent_hash", string.Empty);
            XmlText t2 = doc.CreateTextNode(this.agentHash());
            p2.AppendChild(t2);
            XmlElement p3 = doc.CreateElement(string.Empty, "pause_type", string.Empty);
            XmlText t3 = doc.CreateTextNode(pause);
            p3.AppendChild(t3);

            p.AppendChild(p1);
            p.AppendChild(p2);
            p.AppendChild(p3);
            request.AppendChild(p);
            doc.AppendChild(request);

            XmlDocument response = send_request(doc);
            //XmlNodeList lista = response["response"]["getpauses_response"].ChildNodes;
        }


        public void unpauseAgent()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement request = doc.CreateElement(string.Empty, "request", string.Empty);
            XmlElement p = doc.CreateElement(string.Empty, "unpauseagent", string.Empty);
            XmlElement p1 = doc.CreateElement(string.Empty, "agent_number", string.Empty);
            XmlText t1 = doc.CreateTextNode(this.agente);
            p1.AppendChild(t1);
            XmlElement p2 = doc.CreateElement(string.Empty, "agent_hash", string.Empty);
            XmlText t2 = doc.CreateTextNode(this.agentHash());
            p2.AppendChild(t2);


            p.AppendChild(p1);
            p.AppendChild(p2);
            request.AppendChild(p);
            doc.AppendChild(request);

            XmlDocument response = send_request(doc);
        }

        /*public String getcampaigninfo()
        {
        }*/

    }
}
